import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
Vue.use(Router)
// 引入多个模块的规则
import node from './modules/node'
import order from './modules/order'
import policy from './modules/policy'
import report from './modules/report'
import sku from './modules/sku'
import task from './modules/task'
import user from './modules/user'
import vm from './modules/vm'
/* Layout */
import Layout from '@/layout'

export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [{
      path: 'home',
      name: 'home',
      component: () => import('@/views/home/index.vue'),
      meta: { title: '帝可得', icon: 'home' }
    }]
  },
  // 404 page must be placed at the end !!!
  { path: '*', redirect: '/404', hidden: true }
]
// 动态路由
export const asyncRoutes = [
  task,
  node,
  vm,
  user,
  sku,
  policy,
  order,
  report
]
// 声明白名单页面
const whiteList = ['/login', '/404']

const createRouter = () => new Router({
  scrollBehavior: () => ({ y: 0 }),
  routes: [...constantRoutes, ...asyncRoutes] // 临时合并所有的路由
})

const router = createRouter()

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否已登入 如果登录不能前往登录页
  if (store.getters.userToken && to.path === '/login') {
    next('/')
  } else {
    next()
  }
  // 判断是否为登录  前往白名单页面  是的就放行 不是就阻止登录
  if (!store.getters.userToken && whiteList.includes(to.path)) {
    next()
  } else if (!store.getters.userToken) {
    next('/login')
  }
})
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
